import React, { Fragment } from 'react'
import {
  View,
  StyleSheet,

  Text,
  ScrollView
} from 'react-native'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CompanyHeader from './components/CompanyHeader'
import CompanyBody from './components/CompanyBody'
import { ONE_PIXEL } from '@/utils/ScreenUtil'
import {
  updateCompanyInfo,
  myCompanyBaseInfo
} from 'src/utils/RequestAPI'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
/* redux */
import { connect } from 'react-redux'

import { DO_REQUEST_CHANGE_COMPANY_INFO_ACTION, DO_REQUEST_MAIN_PAGE_B_ACTION } from 'src/pageB/main/main-page/store/action'
import { showTipModal } from 'src/utils/ModalUtil'
import CustomButton from 'src/components/button/CustomButton'

const mapActiontoProps = dispatch => ({
  doRequestUserCompanyApplyApply(payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUpdateCompanyInfo(...payload) {
    const promise = DO_REQUEST_CHANGE_COMPANY_INFO_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  }
})
@connect(
  ({ userinfo, mineCompanyStore, BMineCenterStore }) => ({
    userinfo,
    haveCompanyApply: BMineCenterStore.haveCompanyApply,
    company: BMineCenterStore.company,
    ...mineCompanyStore
  }),
  mapActiontoProps
)
class BMineCompany extends BasePage {
  state = {
    header: {
      headerBg: 'transparent'
    },
    data: {}
  }

  childRender() {
    const { OrgCompanyDO, haveCompanyApply } = this.props
    const { data } = this.state
    return (
      <ScrollView style={styles.container}>
        <CompanyHeader
          data={data}
          companyId={haveCompanyApply.companyId}
          jumpCompanyAvator={this.jumpCompanyAvator}
          jumpBCompanyNameSample={this.jumpBCompanyNameSample}
          masterCompanyPress={this.masterCompanyPress}
          slaveCompanyPress={this.slaveCompanyPress} />
        <CompanyBody
          companyId={haveCompanyApply.companyId}
          data={data}
          jumpFn={this.jumpFn}
          getData={this.getData}
          jumpCompanyWelfare={this.jumpCompanyWelfare}
          CommonInputPage={this.CommonInputPage}
          slaveCompanyCheck={this.slaveCompanyCheck} />
      </ScrollView>
    )
  }

  renderNavigationBarChild = () => {
    return (
      <CustomButton style={[styles.naviBtnBG]} onPress={this.prewClick}>
        <Text>预览</Text>
      </CustomButton>
    )
  }

  componentDidMount() {
    ShowLoading()
    this.getMyCompanyBaseInfo().finally(() => {
      DismissLoading()
    })
  }

  componentWillUnmount() {
    super.componentWillUnmount()
    if (this.props.company.completeDegree !== '100%') {
      const { userinfo: { userId }, doRequestUserCompanyApplyApply } = this.props
      doRequestUserCompanyApplyApply({ userId })
    }
  }

  slaveCompanyCheck = () => {
    // 关联企业不可以修改
    const { data: { canNotEdit } } = this.state
    if (canNotEdit) {
      this.slaveCompanyPress()
      return true
    }
  }

  getMyCompanyBaseInfo = () => {
    const { haveCompanyApply: { companyId } } = this.props
    return myCompanyBaseInfo({ headers: { companyId } }).then((res) => {
      // 判断基本信息填写几项
      let data = res.data
      if (data) {
        data.BaseInfoSize = this.prewBaseInfoSize(data)
        data.companyAddress = data.areaProvince == data.areaCity ? data.areaCity + data.addressArea + data.addressDetail : data.areaProvince + data.areaCity + data.addressArea
        // 福利字段进行处理
        let benefitsSize
        try {
          let benefits = (JSON.parse(data.benefits) || []).length
          benefitsSize = `已选${benefits}项`
        } catch (error) {
          benefitsSize = null
        }
        data.benefitsSize = benefitsSize
        data.companyPicUrl = (data.companyPicUrl.split(',') || []).filter(e => e)
        data.companyInfoLength = (data.companyInfo || '').length + '字'
        data.famousStatus = data.famousId ? '去查看' : '去申请'
        data.canNotEdit = !!(data.famousId && !data.isMaster)
        this.setState({
          data: data
        })
      }
    })
  }

  // 预览完善度
  prewBaseInfoSize = ({ addressDetail, companyInfo, companyAbout, companyFinance, companyPerson }, tip = false) => {
    let BaseInfoSize = 0
    const checks = [
      {
        key: addressDetail,
        value: '企业地址'
      },
      {
        key: companyInfo,
        value: '企业简介'
      },
      {
        key: companyAbout,
        value: '行业'
      },
      {
        key: companyFinance,
        value: '融资阶段'
      },
      {
        key: companyPerson,
        value: '人员规模'
      }
    ].every(e => {
      if (e.key) {
        ++BaseInfoSize
      } else {
        tip && CommonToast(`请完善${e.value}信息`)
      }
      return e.key
    })
    return BaseInfoSize
  }

  /* 预览 */
  prewClick = () => {
    const { data } = this.state
    if (data.BaseInfoSize === 5) {
      const { haveCompanyApply } = this.props
      this.props.navigation.navigate('CompanyHomepage', {
        data,
        companyId: haveCompanyApply.companyId
      })
    } else {
      this.prewBaseInfoSize(data, true)
    }
  }

  /* 主管企业提示 */
  masterCompanyPress = () => {
    const tipTxt = {
      color: '#444444',
      fontSize: ScaleT(16),
      lineHeight: ScaleS(26)
    }
    this.tipPrompModal = showTipModal({
      contentText: '您是当前名企的主管企业，拥有管理该名企的权益，权益包含：',
      confirmText: '知道了',
      cancelText: null,
      onConfirm: () => {
        this.tipPrompModal.close()
        this.tipPrompModal = null
      },
      children: <View style={{
        marginTop: ScaleS(-30),
        padding: ScaleS(20)
      }}>
        <Text style={tipTxt}>1. 可以修改包括基本信息、公司福利、公司相册、以及slogan；</Text>
        <Text style={tipTxt}>2. 查看名企关联企业；</Text>
        <Text style={tipTxt}>3. 有权删除关联企业； </Text>
        <Text style={tipTxt}>4. 通过客服添加关联企业</Text>
      </View>
    })
  }

  /* 关联企业提示 */
  slaveCompanyPress = () => {
    this.tipPrompModal = showTipModal({
      contentText: '您是当前名企的关联企业，关联企业不可对名企相关信息进行修改',
      confirmText: '知道了',
      cancelText: null,
      onConfirm: () => {
        this.tipPrompModal.close()
        this.tipPrompModal = null
      }
    })
  }

  /* 公司简称 */
  jumpBCompanyNameSample = ({ data }) => {
    if (this.slaveCompanyCheck()) {
      return
    }
    const { doRequestUpdateCompanyInfo, haveCompanyApply: { companyId } } = this.props
    const saveCallback = simpleName => {
      if (simpleName) {
        doRequestUpdateCompanyInfo({ params: { simpleName, companyId } }).then(() => {
          CommonToast('保存成功')
          this.getMyCompanyBaseInfo()
        })
      }
    }
    this.props.navigation.navigate('CommonInputPage', {
      title: '企业简称',
      desc: '*请填写企业简称',
      placeholder: '请输入',
      maxLength: 10,
      value: data.simpleName || '',
      saveCallback
    })
  }

  /* 公司头像 */
  jumpCompanyAvator = ({ name, uri }) => {
    if (this.slaveCompanyCheck()) {
      return
    }
    this.props.navigation.navigate('CompanyAvator', {
      userName: name, userAvator: uri, getData: this.getData
    })
  }

  getData = (items, query, Fn, companyId, noToast) => {
    const { haveCompanyApply } = this.props
    updateCompanyInfo({ params: { ...query, companyId: haveCompanyApply.companyId } }).then((e) => {
      if (e.data === true) {
        this.getMyCompanyBaseInfo()
        this.props.navigation.navigate('BMineCompany')
        Fn(false)
        if (!noToast) {
          CommonToast('保存成功')
        }
        return e
      }
    })
  }

  CommonInputPage = (jump, item, name, companyId) => {
    if (this.slaveCompanyCheck()) {
      return
    }
    const saveCallback = value => {
      if (typeof name === 'string') {
        const params = {
          [name]: value,
          companyId
        }
        updateCompanyInfo({ params }).then((e) => {
          if (e.data === true) {
            CommonToast('保存成功')
            this.getMyCompanyBaseInfo()
          }
        })
      }
    }
    this.props.navigation.navigate(jump, {
      ...item,
      saveCallback
    })
  }

  /* 公司福利 */
  jumpCompanyWelfare = (jump) => {
    if (this.slaveCompanyCheck()) {
      return
    }
    const { data = {} } = this.state
    const { haveCompanyApply } = this.props
    this.props.navigation.navigate(jump, { welfareItemList: data.benefits, companyId: haveCompanyApply.companyId, getMyCompanyBaseInfo: this.getMyCompanyBaseInfo })
  }

  jumpFnCheckRouters = ['BusinessAddress', 'BusinessIndustry']

  jumpFn = (jump, data = {}) => {
    if (this.jumpFnCheckRouters.includes(jump) && this.slaveCompanyCheck()) {
      return
    }
    const getData = this.getData
    const { haveCompanyApply } = this.props
    this.props.navigation.navigate(jump, { ...data, getData, companyId: haveCompanyApply.companyId, getMyCompanyBaseInfo: this.getMyCompanyBaseInfo })
  }
}

export default BMineCompany

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF'
  },
  naviBtnBG: {
    width: ScaleS(58),
    height: ScaleS(28),
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: ScaleS(20),
    borderRadius: ScaleS(14),
    fontSize: ScaleT(12),
    fontWeight: '600',
    color: '#000000',
    backgroundColor: 'rgba(255,255,255,0.8)',
    alignSelf: 'flex-end'
  }
})
